//
//  ST_SeekPreferenceViewController.swift
//  btvideo
//
//  Created by mac on 2020/5/7.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit
import HandyJSON
import RxCocoa
import RxSwift
import Contacts

//想要 寻找
class ST_SeekPreferenceViewController: UIViewController,ST_RegisterRouteProtocol {

    var imageArray: [RegisterFriendForCellModel] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
        
        view.addSubview(progress_view)
        progress_view.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(statusBarHeight + 25)
            make.height.equalTo(2)
        }
        
        view.addSubview(seekTitleLabel)
        seekTitleLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(progress_view.snp.bottom).offset(26)
        }
        
        view.addSubview(sub_title_label)
        sub_title_label.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(seekTitleLabel.snp.bottom).offset(4)
        }
        
        view.addSubview(collectionView)
        view.addSubview(start_btn)
        
        collectionView.snp.makeConstraints { (make) in
            make.top.equalTo(sub_title_label.snp.bottom).offset(33)
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        
        start_btn.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().offset(-BTSafeAreaBottom-46)
            make.centerX.equalToSuperview()
            make.width.equalTo(260)
            make.height.equalTo(44)
        }
        
        binding()
        
        pull_observer.onNext(())
        
        
        back_thread_execute(afterDelay: 1) {
            ST_RegisterMonitor.shared.logger.report(fromController: self)
        }
    }
    
    
    fileprivate func binding(){
           
       Observable.combineLatest(pull_observer, SCComponets.config_component.boot_config_observer).subscribe(onNext: {[weak self] _ , state in
           
           if state == .finished{
               self?.request_data()
           }
           
       }).disposed(by: disposeBag)
        
   }
    
    fileprivate func request_data(){
        
        JVrequest(PH.getFindAndAgeApi, success: { (json) in
            
            if let want_findList = [SeekPreferenceModel].deserialize(from: json["data"]["want_find"].rawString() ?? "") as? [SeekPreferenceModel]{
                
                self.data_array = want_findList
                
                for index in 0...2 {
                    let model = RegisterFriendForCellModel()
                    switch index {
                    case 0:
                        model.image = ST_ImageUtils.imageName("seekfor_1")
                        for m in self.data_array {
                            if m.name == "短期关系" {
                                model.id = m.id
                            }
                        }
                    case 1:
                        model.image = ST_ImageUtils.imageName("seekfor_2")
                        for m in self.data_array {
                            if m.name == "谈甜甜的恋爱" {
                                model.id = m.id
                            }
                        }
                    case 2:
                        model.image = ST_ImageUtils.imageName("seekfor_3")
                        for m in self.data_array {
                            if m.name == "字母" {
                                model.id = m.id
                            }
                        }
                    default:
                        break
                    }
                    model.isSelect = false
                    self.imageArray.append(model)
                }
                
                self.collectionView.reloadData()
                
            }
            
        }) { (code, err) in
            
            main_thread_execute(afterDelay: 1.5) {
                self.pull_observer.onNext(())
            }
        }
    }
    

//    MARK: - properties
    
    var disposeBag = DisposeBag()
        
    fileprivate let pull_observer = PublishSubject<Void>()
    
    fileprivate lazy var progress_view: registerProgressView = {
        let v = registerProgressView()
        v.setProgress(currentIndex: 1, amount: 4)
        return v
    }()
    
    fileprivate lazy var seekTitleLabel:UILabel = {
        let control = UILabel.init()
        control.text = "你想建立的感情关系是？"
        control.textColor = Color.init(hexString: "#333333")
        control.numberOfLines = 0
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.medium)
        return control
    }()

    fileprivate lazy var sub_title_label: UILabel = {
        let l = UILabel()
        l.text = "真诚有助于找到自己真正想要的"
        l.textColor = Color.init(hexString: "#999999")
        l.numberOfLines = 0
        l.textAlignment = .center
        l.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        return l
    }()
    
    fileprivate lazy var start_btn:UIButton = {
       
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.cornerRadius = 22

        
        control.setBackgroundImage(UIImage.init(color: UIColor.init(hex: 0xFEC207)!, size: CGSize.init(width: 1, height: 1)), for: UIControl.State.normal)
        
        control.setBackgroundImage(UIImage.init(color: UIColor.init(hex: 0xDFE3E9)!, size: CGSize.init(width: 1, height: 1)), for: UIControl.State.disabled)
        
        control.setTitleForAllStates("下一步")
        
        control.setTitleColorForAllStates(UIColor.white)
        
        control.setTitleColor(UIColor.white, for: UIControl.State.disabled)
        
        control.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        
        control.isEnabled = false
        
        control.addTarget(self, action: #selector(start_action), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    
    fileprivate lazy var layout: UICollectionViewFlowLayout = {
       let l = UICollectionViewFlowLayout()
//        l.sectionInset = UIEdgeInsets.init(top: 0, left: 38, bottom: 0, right: 37)
        l.itemSize = CGSize.init(width: ScreenWidth, height: TIANCompatibleValue(value: 156))
        l.minimumLineSpacing = 10
        return l
    }()
    
    fileprivate lazy var collectionView: UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: layout)
        control.backgroundColor = .clear
        control.delegate = self
        control.dataSource = self
        control.register(cellWithClass: RegisterFriendForCollectionViewCell.self)
        control.alwaysBounceVertical = true
        control.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: BTSafeAreaBottom+46+44+10, right: 0)
        return control
    }()
    
    fileprivate var data_array = [SeekPreferenceModel]()
    
    fileprivate var current_selected_index_path: IndexPath? {
        didSet {
            self.start_btn.isEnabled = current_selected_index_path != nil
        }
    }
}

//MARK: - UICollection Delegate
extension ST_SeekPreferenceViewController:UICollectionViewDelegate,UICollectionViewDataSource{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withClass: RegisterFriendForCollectionViewCell.self, for: indexPath)
        
        cell.bind(data: imageArray[safe: indexPath.row])
//        cell.model = data_array[indexPath.row]
        
        return cell
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
//        collectionView.cellForItem(at: indexPath)?.isSelected = true
        
        for index in 0 ..< imageArray.count {
            imageArray[index].isSelect = false
        }
        imageArray[indexPath.row].isSelect = true
        
        collectionView.reloadData()
        
        current_selected_index_path = indexPath
    }
    
    
//    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
//
//        current_selected_index_path = nil
//    }
    
}

//MARK: - Event
extension ST_SeekPreferenceViewController {
    
    @objc func start_action(){
        
        guard let row = current_selected_index_path?.row , let m = imageArray[safe:row] else {
            return
        }
        
//        JVrequest(PH.registerAvatarApi,parameters: ["want_find":m.id] ,success: { (json) in
//
//            self.hidden_indeterminate_h_u_d()
//
////            self.navigationController?.pushViewController(SexPreferenceViewController())
//            //TianRegisterStepManager.shared.pushNextStepAction()
//
//        }) { (code, err) in
//
//            ToastHud(text: err, view: self.view)
//        }
        
        
        pushNextRegisterController(parameters: ["want_find": m.id])

    }
}

//MARK: - Model
class SeekPreferenceModel:NSObject,HandyJSON {
    
    var id:Int = 0
    var name:String = ""
    
    required override init() {
        super.init()
    }
}


//MARK: - Cell
class SeekPreferenceCell: UICollectionViewCell {

    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.backgroundColor = .clear
        
        contentView.addSubview(statusBtn)
        statusBtn.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    fileprivate lazy var statusBtn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setBackgroundImage(UIImage.init(color: UIColor.init(hex: 0xDFE3E9)!, size: CGSize.init(width: 1, height: 1)), for: UIControl.State.normal)
        control.setBackgroundImage(UIImage.init(color: UIColor.init(hex: 0xFEC207)!, size: CGSize.init(width: 1, height: 1)), for: UIControl.State.selected)
        control.cornerRadius = 30
        control.setTitleColorForAllStates(UIColor.init(hex: 0x333333)!)
        control.setTitleColor(UIColor.white, for: UIControl.State.selected)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        control.isUserInteractionEnabled = false
        return control
    }()
    
//    override var isHighlighted: Bool{
//        didSet{
//            statusBtn.isSelected = isHighlighted
//        }
//    }
    
    override var isSelected: Bool{
        didSet{
            statusBtn.isSelected = self.isSelected
        }
    }
    
    
    var model = SeekPreferenceModel(){
        didSet{
            statusBtn.setTitleForAllStates(model.name)
        }
    }
    
}






//MARK:- Sex Preference

class SexPreferenceViewController: ST_SeekPreferenceViewController {
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //ST_BTGlobalDataCenter.shared.beginLogPageView("GoalOfAge")
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        //ST_BTGlobalDataCenter.shared.endLogPageView("GoalOfAge")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        seekTitleLabel.text = "你理想的对象年龄范围"
        
    }
    
    override func request_data() {
        
        JVrequest(PH.getFindAndAgeApi, success: { (json) in
            
            if let want_findList = [SeekPreferenceModel].deserialize(from: json["data"]["age_range"].rawString() ?? "") as? [SeekPreferenceModel]{
                
                self.data_array = want_findList
                
                self.collectionView.reloadData()
                
            }
            
        }) { (code, err) in
            
            main_thread_execute(afterDelay: 1.5) {
                self.pull_observer.onNext(())
            }
        }
        
    }
    
    override func start_action() {
        
        
        guard let row = current_selected_index_path?.row , let m = data_array[safe:row] else {
            return
        }
        
        pushNextRegisterController(parameters: ["age_range":m.id])
        
//        self.show_indeterminate_h_u_d()
//
//        JVrequest(PH.registerAvatarApi,parameters: ["age_range":m.id] ,success: { (json) in
//
//            self.hidden_indeterminate_h_u_d()
//
//
//            //TianRegisterStepManager.shared.pushNextStepAction()
//
//
//        }) { (code, err) in
//
//            ToastHud(text: err, view: self.view)
//        }
//
        
    }
    
}
